package com.baitiaojun.gateway.filter;

import lombok.NonNull;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpHeaders;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpRequestDecorator;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * @类名 Filter
 * @作者 白条君
 * @创建日期 2022/12/1 00:18
 * @版本 1.0
 */
@Order(0)
@Component
public class AvoidMemorySoarFilter implements GlobalFilter {

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest oldRequest = exchange.getRequest();
        ServerHttpRequest build = oldRequest.mutate().build();
        HttpHeaders headers = new HttpHeaders();
        headers.putAll(exchange.getRequest().getHeaders());
        build = new ServerHttpRequestDecorator(build) {
            @Override
            public @NonNull HttpHeaders getHeaders() {
                return headers;
            }
        };
        return chain.filter(exchange.mutate().request(build).build());
    }
}
